const imagesBase64 = require("./src/js/imagesBase.js");
// imagesBase64().then(res=>{console.log(res)});
// return
const imagesResult = require("./src/js/face.js")
const Koa = require("koa");
const Router = require("@koa/router")
// const bodyParser = require("koa-bodyparser");
const multer = require("@koa/multer");
const serve = require("koa-static")
// 跨域问题
const cors = require("@koa/cors");

const app = new Koa();
const router = new Router();

var storage = multer.diskStorage({
	destination: function(req, file, cb) {
		cb(null, "public/uploads")
	},
	filename: function(req, file, cb) {
		const filetype = file.originalname.split(".");
		cb(null, Date.now() + "." + filetype[filetype.length-1])
	}
})
const upload = multer({
	storage: storage
});

// 上传图片
router.post("/upload", upload.fields([{
	name: 'avator',
	maxCount: 1
}]), async (ctx, next) => {
	// 如何实现'用户上传图片'
	// ctx.file.path拿到存在服务器上图片的路径
	// 将图片转化成base64位的编码
	// 再上传到腾讯云上识别
	try{
		await next();
		let uri = await imagesBase64(ctx.files.avator[0].path);
		// console.log(uri)
		let res = await imagesResult(uri)
		console.log('ctx.request.files', ctx.request.files);
		// console.log('ctx.files', ctx.files.avator[0].path);
		console.log('ctx.request.body', ctx.request.body)
		let { Age,Gender,Beauty } = res.FaceInfos[0].FaceAttributesInfo;
		console.log(Object.prototype.toString.call(res))
		// ctx.body = res
		let images = ctx.request.files.avator[0].filename;
		// ctx.body = images
		// ctx.body = ctx.origin
		// 图片的路径
		// const basename = path.basename(images.path);
		// ctx.body = basename;
		// console.log('basename',basename)
		let resd = `${ctx.origin}/uploads/${images}`;
		// console.log('resd',resd)
		
		ctx.body = {
			code:200,
			data:{
				url:resd,
				Age:Age,
				Gender:Gender,
				Beauty:Beauty
			}
		}
	}catch(e){
		ctx.body = {
			code:500,
			msg:'没有检测到人脸',
			data:{
				
			}
		}
	}
	
})

// 解决跨域问题
app.use(cors());

// 配置静态资源访问目录
app.use(serve("./public"))

// 把定义好的路由,注册到app对象中
app.use(router.routes());
app.use(router.allowedMethods());

// 设置全局权限,避免跨域
app.use((ctx, next) => {
	ctx.set("Access-Control-Allow-Origin", "*");
	next();
})

app.listen(3000);
console.log("listening on http://localhost:3000")
